<?php
namespace app\home\controller;

use app\common\model\User as U;
use app\common\validate\User as UserValidate;
use  app\common\validate\Article;
use think\Db;
class Ucenter extends Base
{

  public function index()
  {
    if(request()->isAjax()){
      $data = input("post.");
      if(!isMobileNum($data["mobile"])){
        return json(["code" => 0, "msg" => "手机号格式不正确"]);
      }
      if(!isEmail($data["email"])){
        return json(["code" => 0, "msg" => "邮箱格式不正确"]);
      }
      $update = Db::name("user")->where("uid",session("loginUid"))->update($data);
      if($update){
        return json(["code" => 1, "msg" => "修改成功"]);
      }
      return json(["code" => 0, "msg" => "修改失败"]);
    }else{
      return view();
    }
  }
  //图片上传
  public function uploads()
  {
    $file = request()->file('Image');
    if($file){
      $info = $file->validate(['size'=>5*1024*1024,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' .DS .input("path"));
      if($info){
        $savePath = DS . 'uploads' .DS .input("path") .DS .$info->getSaveName();
        $saveFace = Db::name("user")->where("uid",session("loginUid"))->update(["face"=>$savePath]);
        if($saveFace){
          return json([ "code" =>1 ,'url' => $savePath,"msg" =>"上传成功"]);
        }
      }else{
        return json([ "code" =>0 ,"msg" => $file->getError()]);
      }
    }
  }

  //密码修改
  public function rePassword()
  {
    if(request()->isAjax()){
      $data = input("post.");
      $UserValidate = new UserValidate();
      if($UserValidate->scene("rePassword")->check($data)){
        if($data["password"] != $data["repwd"]){
         return ["code" => 0, "msg" => "两次密码不一致"];
        }
        if(U::where("uid" ,session("loginUid"))->value("password") == md5($data["oldPassword"])){
          $update = U::where("uid" ,session("loginUid"))->update(["password"=>md5($data["password"])]);
          if($update){
            return ["code" => 1, "msg" => "修改成功"];
          }
          return ["code" => 0, "msg" => "修改失败"];
        }
        return ["code" => 0, "msg" => "旧密码不正确"];
      }
      return ["code" => 0, "msg" => $UserValidate->getError()];
    }else {
      return view('reset_password');
    }
  }
  public function exitLogin()
  {
    session("loginUid",null);
    $this ->success("已退出登录","/");
  }

  //发布文章/修改文章
  public function release()
  {
    $id = input("id");
    $title = input("title","","strip_tags");
    $tag = input("tag");
    $content = input("content");
    if(request()->isAjax()){
      preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',input("content","","trim"), $ereg);//正则表达式把图片的SRC获取出来了
      if(empty($ereg)) {
        $img = "";
      }else{
        $img = $ereg[1];//图片SRC
      }
      $data["title"] = $title;
      $data["uid"] = session("loginUid");
      $data["content"] = $content;
      $data["create_time"] = time();
      $data["category_id"] = $tag;
      $data["img"] = $img;
      $ArticleValidate = new Article();
      if (!$ArticleValidate->check($data)){
        return json(["code" => 0,"msg" =>$ArticleValidate->getError()]);
      }
      if($id > 0){
        $update = Db::name("article")->where("article_id",$id)->update($data);
        if($update){
          return json(["code" => 1,"msg"=>"修改成功"]);
        }
        return json(["code" => 0,"msg"=>"修改失败"]);
      }else{
        $insert = Db::name("article")->insert($data);
        if($insert){
          return json(["code" => 1,"id" =>$id,"msg"=>"发布成功"]);
        }
        return json(["code" => 0,"msg"=>"发布失败"]);
      }
    }else{
      if($id > 0){
        $articleDetail = Db::name("article")->where("article_id",$id)->find();
        $articleDetail["content"] = str_replace("\r\n", '',$articleDetail["content"]);
      }else{
        $articleDetail = "";
      }
      $tagList = Db::name("category")->select();
      return view("",["tagList" => $tagList,"articleDetail" => $articleDetail]);
    }
  }
  //文章列表
  public function articleList()
  {
    $articleList = Db::name("article")->order('article_id desc')->where("uid",session("loginUid"))->paginate(5,false,['query'=>request()->param()])->each(function($item, $key){
      $userId = $item["uid"];
      $tagId = $item["category_id"];
      $username = Db::name('user')->where("uid",$userId)->value("username");
      $tagName = Db::name('category')->where("id",$tagId)->value("category_name");
      $item['usrname'] = $username;
      $item['tagName'] = $tagName;
      return $item;
    });
    $page = $articleList->render();
    return view("list",["articleList" => $articleList]);
  }
  //删除文章
  public function delete()
  {

    $articleId = input("articleId");
    $delete = Db::name("article")->where("article_id",$articleId)->delete();
    if($delete){
      return json(["code" => 1,"msg" =>"删除成功"]);
    }else{
      return json(["code" => 0,"msg" =>"删除失败"]);
    }
  }
}